agent: @U0AJM7X8FBR build a feature that would go viral if demoed on TikTok. Th#336
agent: @U0AJM7X8FBR build a feature that would go viral if demoed on TikTok. Th#336sweetmantech wants to merge 2 commits intotestfrom
Conversation
Streams a complete AI-generated music release campaign given artist and song details. Returns 6 sections in real-time (press release, Spotify pitch, Instagram captions, TikTok hooks, fan newsletter, curator email) using XML-style section markers parsed by the frontend. - lib/launch/validateLaunchBody.ts — Zod validation for launch body - lib/launch/buildCampaignPrompt.ts — system + user prompt builders - lib/launch/generateCampaignHandler.ts — streamText handler with auth - lib/launch/__tests__/validateLaunchBody.test.ts — 8 passing tests - app/api/launch/route.ts — POST /api/launch route Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
📝 WalkthroughWalkthroughThis PR adds comprehensive JSDoc parameter documentation across the codebase and implements a new release campaign generation endpoint. The campaign feature includes request validation, prompt construction, and streaming AI response handling. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Route as app/api/launch/route.ts
participant Handler as generateCampaignHandler
participant Auth as validateAuthContext
participant Parser as JSON Parser
participant Validator as validateLaunchBody
participant PromptBuilder as buildCampaignPrompt
participant AI as streamText (DEFAULT_MODEL)
participant Response as TextStreamResponse
Client->>Route: POST /api/launch (with body)
Route->>Handler: delegate to generateCampaignHandler(request)
Handler->>Auth: validateAuthContext(request)
alt Auth Failure
Auth-->>Handler: NextResponse (auth error)
Handler-->>Route: return error response
Route-->>Client: 401/403 response
else Auth Success
Auth-->>Handler: auth context valid
Handler->>Parser: parse request body as JSON
alt Parse Failure
Parser-->>Handler: error
Handler-->>Route: return parse error response
Route-->>Client: 400 response
else Parse Success
Parser-->>Handler: json object
Handler->>Validator: validateLaunchBody(json)
alt Validation Failure
Validator-->>Handler: NextResponse {status: error, missing_fields, error}
Handler-->>Route: return validation error
Route-->>Client: 400 response with error details
else Validation Success
Validator-->>Handler: validated LaunchBody
Handler->>PromptBuilder: buildCampaignSystemPrompt()
PromptBuilder-->>Handler: system prompt string
Handler->>PromptBuilder: buildCampaignUserPrompt(validated)
PromptBuilder-->>Handler: user prompt string
Handler->>AI: streamText({system, messages: [{role: user, content: userPrompt}]})
AI-->>Handler: result with streaming text
Handler->>Response: result.toTextStreamResponse({headers: getCorsHeaders()})
Response-->>Handler: streaming Response
Handler-->>Route: return Response
Route-->>Client: 200 with streamed campaign content
end
end
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes The bulk of the changes are homogeneous—consistent JSDoc parameter additions across 50+ files, which require minimal individual reasoning. However, four new feature files introduce a cohesive but non-trivial campaign generation workflow combining validation, prompt engineering, and streaming AI responses. The logic density is moderate (Zod schemas, prompt templates, handler orchestration), but the patterns are straightforward with clear error handling paths. Possibly related PRs
Poem
🚥 Pre-merge checks | ❌ 1❌ Failed checks (1 warning)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
app/api/transcribe/route.ts (1)
11-33:⚠️ Potential issue | 🔴 CriticalEnforce authenticated account resolution instead of trusting
account_idfrom body.Line 12/17-19 and Line 27-30 currently let the caller pick the account, and the route does not use
validateAuthContext()or a Zod validate function. This creates an authorization bypass risk and breaks route auth/validation conventions.As per coding guidelines, API routes must “Always use
validateAuthContext()for authentication,” “Never useaccount_idin request bodies,” and “use a validate function for input parsing using Zod.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/api/transcribe/route.ts` around lines 11 - 33, Replace trusting account_id from the request body with enforced authentication: call validateAuthContext() at the start of the handler, drop using body.account_id and instead pass authContext.accountId (or equivalent) into processAudioTranscription as ownerAccountId; additionally add input validation using a Zod schema (validate function) to parse/validate audio_url, title, include_timestamps and artist_account_id (or resolve artistAccountId from auth if required) before calling processAudioTranscription; ensure all early returns use NextResponse.json with 400 on schema validation failures and do not accept account_id from the client.lib/mcp/tools/transcribe/registerTranscribeAudioTool.ts (1)
8-13:⚠️ Potential issue | 🔴 CriticalRemove caller-supplied
account_idfrom tool input and resolve it from auth context.Line 10 and Line 34 currently trust client-provided
account_id, which allows cross-account writes if spoofed. This should be derived viaresolveAccountId()using authenticated context, and only keep explicit overrides where access is validated.As per coding guidelines, MCP tools “should never manually extract
accountId… always useresolveAccountId()for validation and access control,” and “Never useaccount_idin request bodies or tool schemas; always derive the account ID from authentication.”Also applies to: 30-35
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/mcp/tools/transcribe/registerTranscribeAudioTool.ts` around lines 8 - 13, Remove the caller-supplied account_id from the transcribe tool input schema and any use in the handler: delete the account_id field from transcribeAudioSchema and from any request-body parsing, and instead call resolveAccountId(authContext) inside the registerTranscribeAudioTool handler (or the function that processes the tool input) to derive and validate the account ID; ensure any downstream calls that previously used the client-provided account_id (e.g., storage or DB writes) now receive the resolved value, and remove/ignore any code paths that accept an explicit artist_account_id override unless you also validate it against the resolved account via the existing access-control checks.lib/transcribe/processAudioTranscription.ts (1)
18-21:⚠️ Potential issue | 🔴 CriticalGuard
fetch(audioUrl)against SSRF and hanging upstream calls.Line 18 fetches a caller-controlled URL without network restrictions or timeout. That can be abused for internal network probing and can also tie up resources on slow/unresponsive endpoints.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/transcribe/processAudioTranscription.ts` around lines 18 - 21, Validate and guard the fetch of caller-controlled audioUrl in processAudioTranscription: first parse and allowlist the URL scheme/hostname (reject non-http(s) and hostnames that resolve to private/reserved IPs or loopback addresses), then perform the fetch with an AbortController-based timeout (pass signal to fetch) and sensible options (GET, limited redirects) so slow/unresponsive upstreams are bounded; ensure you handle abort errors and surface a clear error if validation or the timed fetch fails rather than directly calling fetch(audioUrl) unguarded.lib/credits/getCreditUsage.ts (1)
24-25:⚠️ Potential issue | 🟡 MinorRemove type-unsafe
as anycasts and non-existent property checks.The AI SDK v6.0.0-beta.122 uses
promptTokensandcompletionTokensas the coreLanguageModelUsageproperties. The code currently checks for non-existentinputTokens/outputTokensproperties first, which never exist, then falls back to the correct properties. While this works, it violates TypeScript best practices and masks the actual API.Replace with:
const inputTokens = usage.promptTokens ?? 0; const outputTokens = usage.completionTokens ?? 0;Update the comment to reflect that v6 uses
promptTokens/completionTokens, not v2/v3 naming variants.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/credits/getCreditUsage.ts` around lines 24 - 25, Replace the type-unsafe casts and legacy property checks in getCreditUsage (the inputTokens/outputTokens assignment) by reading the canonical v6 properties directly: use usage.promptTokens and usage.completionTokens with a numeric fallback (e.g., ?? 0) instead of casting to any or checking inputTokens/outputTokens; also update the nearby comment to state that AI SDK v6 uses promptTokens/completionTokens (not v2/v3 naming) so future readers know the correct property names.
🧹 Nitpick comments (23)
lib/content/isCompletedRun.ts (1)
8-11: Add meaningful JSDoc text (current block is effectively empty).On Line 8-11, the comment exists but doesn’t explain behavior or the
runparameter. Please add a short summary and a concrete@paramdescription so the docs are actually useful.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/content/isCompletedRun.ts` around lines 8 - 11, Update the empty JSDoc block above the isCompletedRun function to include a short summary sentence describing what the function does (e.g., checks whether a run is finished), a concrete `@param` entry for the run parameter explaining expected shape or properties used (e.g., status field or timestamps) and how it is interpreted, and an `@returns` description specifying the boolean result and what true/false mean; reference the isCompletedRun identifier so the doc directly documents that function's behavior.lib/github/getRepoGitModules.ts (1)
7-12: Fix inconsistent JSDoc param paths for destructured input.Line 7, Line 11, and Line 12 add nested tags (
owner.owner,owner.repo,owner.branch) that conflict with the existing flat tags (owner,repo,branch). This makes the docs ambiguous for IDE/tooling.Suggested JSDoc cleanup
/** * Fetches and parses .gitmodules from a GitHub repository. * Uses the GitHub Contents API (works for both public and private repos). * - * `@param` owner.owner - * `@param` owner - The GitHub repository owner - * `@param` repo - The GitHub repository name - * `@param` branch - The branch to fetch from - * `@param` owner.repo - * `@param` owner.branch + * `@param` params - Repository coordinates + * `@param` params.owner - The GitHub repository owner + * `@param` params.repo - The GitHub repository name + * `@param` params.branch - The branch to fetch from * `@returns` Array of submodule entries, or null if .gitmodules doesn't exist or fetch fails */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/github/getRepoGitModules.ts` around lines 7 - 12, The JSDoc for getRepoGitModules.ts uses inconsistent param names (both flat tags like `@param` owner/@param repo/@param branch and erroneous nested tags like `@param` owner.owner/@param owner.repo/@param owner.branch); remove the nested/duplicate tags and ensure the JSDoc matches the function signature (document the destructured param either as a single object with a type description or keep separate `@param` entries for owner, repo, branch) so that only the correct identifiers used in the function (owner, repo, branch) are documented.lib/supabase/files/createFileRecord.ts (1)
28-30: Clarify@param paramswith field-level intent.On Line 29,
@param paramsis too terse for an exported Supabase domain function. Add a short object-level description plus key fields to keep the contract self-documenting.Suggested JSDoc improvement
/** * Create a file record in the database * - * `@param` params + * `@param` params - File metadata payload used to persist a row in `files`. + * `@param` params.ownerAccountId - Owning account ID. + * `@param` params.artistAccountId - Artist account ID associated with the file. + * `@param` params.storageKey - Storage object key/path. + * `@param` params.fileName - Original or display file name. + * `@param` params.mimeType - Optional MIME type. + * `@param` params.sizeBytes - Optional file size in bytes. + * `@param` params.description - Optional description. + * `@param` params.tags - Optional tags; defaults to [] when omitted. */As per coding guidelines: “Supabase database functions should import from
@/lib/supabase/serverClientand follow the documented pattern with JSDoc comments, error handling, and return types”.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/supabase/files/createFileRecord.ts` around lines 28 - 30, The JSDoc for the exported Supabase function createFileRecord is too terse—replace the generic "@param params" with an object-level description and explicit key descriptions (e.g., params.bucket, params.key or path, params.size, params.mimeType/contentType, params.userId/uploaderId, params.metadata/extra) so callers know the contract; update the comment block above createFileRecord to list each field, types and short intent (required/optional) and ensure it follows the project pattern for Supabase domain functions importing from "@/lib/supabase/serverClient".lib/composio/getCallbackUrl.ts (1)
22-22: Complete and reorder the new@param optionsJSDoc entry.At Line 22,
@param optionshas no description and comes afteroptions.destination/options.roomId. Put the parent param first and add a short description for cleaner generated docs.✏️ Suggested doc-only cleanup
- * `@param` options.destination - Where to redirect: "chat" or "connectors" - * `@param` options.roomId - For chat destination, the room ID to return to - * `@param` options + * `@param` options - Callback URL options + * `@param` options.destination - Where to redirect: "chat" or "connectors" + * `@param` options.roomId - For chat destination, the room ID to return to🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/composio/getCallbackUrl.ts` at line 22, Move the JSDoc `@param` for the parent "options" above the child params (options.destination and options.roomId) and add a short description; update the JSDoc block for the getCallbackUrl (or the exported function in getCallbackUrl.ts) so it lists "@param options - an object containing callback configuration" (or similar concise text) before "@param options.destination" and "@param options.roomId" to keep param order logical and improve generated docs.lib/admins/privy/getLatestVerifiedAt.ts (1)
8-8: Use repository-approved terminology in JSDoc and add a param description.Line 8 introduces
@param user, but the project standard requiresaccountterminology. Please also include a short description for clarity.🔧 Suggested update
- * `@param` user + * `@param` account Privy account object containing linked_accounts metadata. ... -export function getLatestVerifiedAt(user: User): number | null { - const linkedAccounts = user.linked_accounts; +export function getLatestVerifiedAt(account: User): number | null { + const linkedAccounts = account.linked_accounts;As per coding guidelines, "Use 'account' terminology, never 'entity' or 'user'."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/admins/privy/getLatestVerifiedAt.ts` at line 8, Update the JSDoc for getLatestVerifiedAt to use the repository-approved terminology by renaming the param from "user" to "account" and add a short description; specifically, change the `@param` tag to "@param account" and include one-line text describing that account is the Account object or identifier passed into getLatestVerifiedAt so the doc follows the project's "account" terminology and clarifies the parameter purpose.lib/supabase/storage/uploadFileByKey.ts (1)
7-11: Add meaningful descriptions to each JSDoc@param.The new tags are present, but without descriptions they don’t improve API clarity for callers. Please document expected format/behavior (e.g.,
keypath semantics, defaultcontentType, defaultupsert=false).📝 Proposed JSDoc improvement
/** * Upload file to Supabase storage by key * - * `@param` key - * `@param` file - * `@param` options - * `@param` options.contentType - * `@param` options.upsert + * `@param` key Storage object key/path inside the configured bucket. + * `@param` file File or Blob payload to upload. + * `@param` options Optional upload settings. + * `@param` options.contentType MIME type to store with the object (defaults to `application/octet-stream`). + * `@param` options.upsert Whether to overwrite an existing object at the same key (defaults to `false`). */As per coding guidelines, "Supabase database functions should import from
@/lib/supabase/serverClientand follow the documented pattern with JSDoc comments, error handling, and return types".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/supabase/storage/uploadFileByKey.ts` around lines 7 - 11, Update the JSDoc for the upload function (e.g., uploadFileByKey) to include meaningful descriptions for each param: describe key as the storage path/OCI-style path or bucket-relative path semantics (e.g., "bucket/path/to/file.ext"), file as the File/Blob or Buffer to be uploaded, options as an optional object controlling upload behavior, options.contentType with its default (e.g., "application/octet-stream" or infer from filename) and expected MIME string format, and options.upsert with default false and that it controls overwrite behavior; also ensure the function follows the Supabase pattern by importing the server client from "@/lib/supabase/serverClient" and that the JSDoc mentions thrown errors/return type consistent with other Supabase helpers (e.g., upload result or error).lib/flamingo/getFlamingoPresetsHandler.ts (1)
13-13: Complete the JSDoc@paramtag with a description.The
@paramtag is missing a description, which reduces its documentation value. While TypeScript provides type information, a brief description helps clarify the parameter's purpose and maintains consistency with the@returnstag below.📝 Suggested improvement
- * `@param` request + * `@param` request - The incoming HTTP request object containing headers for authentication.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/flamingo/getFlamingoPresetsHandler.ts` at line 13, Add a concise description to the JSDoc `@param` for the request parameter in getFlamingoPresetsHandler: state what the request represents (e.g., incoming Express/HTTP request or handler input), what properties are expected/used (if any), and its role in the function; update the JSDoc `@param` line to read something like "@param request - the incoming request object containing [brief properties or purpose]" so it matches the existing `@returns` documentation and clarifies the parameter's purpose.lib/catalog/getCatalogs.ts (1)
11-14: Complete the JSDoc documentation.The JSDoc comment is incomplete—it lacks a function description, parameter details, and return type documentation. Comprehensive documentation improves maintainability and helps other developers understand the function's purpose, inputs, and outputs.
📝 Proposed fix for complete JSDoc
/** - * - * `@param` accountId + * Fetches all catalogs associated with a specific account. + * + * `@param` accountId - The unique identifier of the account whose catalogs to retrieve + * `@returns` A promise that resolves to a CatalogsResponse containing the list of catalogs + * `@throws` {Error} When the HTTP request fails or the API returns an error status */ export async function getCatalogs(accountId: string): Promise<CatalogsResponse> {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/catalog/getCatalogs.ts` around lines 11 - 14, Add complete JSDoc for the getCatalogs function: write a one-line description of what getCatalogs does, add `@param` accountId with its type and description, document the return value (e.g., Promise of the catalog array or specific Catalog type) with `@returns` and describe possible thrown errors or null cases, and include any side effects; place this above the getCatalogs function declaration in lib/catalog/getCatalogs.ts so the function signature and return type (getCatalogs) are clearly described for callers and maintainers.lib/coding-agent/handleMergeSuccess.ts (1)
10-11: Incomplete JSDoc parameter documentation.The
@param statetag lacks a description. While TypeScript provides type information, a brief description enhances readability and helps developers understand the parameter's purpose without inspecting the type definition.📝 Suggested improvement
* -* `@param` state +* `@param` state - The coding agent thread state containing PR and snapshot information for cleanup */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/coding-agent/handleMergeSuccess.ts` around lines 10 - 11, The JSDoc for the handleMergeSuccess function has an incomplete `@param` tag for "state"; update the comment above handleMergeSuccess in lib/coding-agent/handleMergeSuccess.ts to add a concise description of what the "state" parameter represents (e.g., current merge operation context, contains branch names, commit metadata, and status flags) so readers can understand its purpose without opening the type definition.lib/coding-agent/parseMergeActionId.ts (2)
4-5: Consider adding a description to the@paramtag.The JSDoc
@paramannotation lacks a description. Adding semantic information about the parameter's expected format helps improve documentation clarity.📝 Suggested enhancement
* -* `@param` actionId +* `@param` actionId - The action ID string to parse (format: "merge_pr:owner/repo#123") */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/coding-agent/parseMergeActionId.ts` around lines 4 - 5, The JSDoc for parseMergeActionId is missing a description for the `@param` actionId; update the function's JSDoc block (the one above parseMergeActionId) to describe what actionId should contain (e.g., expected type, format, and any accepted patterns such as "merge:<repo>:<prId>" or a UUID) so callers know the input shape and constraints.
7-11: Consider consolidating similar parsing logic.Both
parseMergeActionIdandparseMergeTestToMainActionIdfollow a similar pattern: validate a prefix/format, extract repository information, and returnnullon mismatch. While they handle different formats, a shared utility function for prefix-based action ID parsing could reduce duplication and improve maintainability. As per coding guidelines, the DRY principle encourages consolidating similar logic into shared utilities.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/coding-agent/parseMergeActionId.ts` around lines 7 - 11, parseMergeActionId duplicates parsing logic used by parseMergeTestToMainActionId; create a shared utility (e.g., parsePrefixedActionId or parseActionIdWithRegex) that accepts the expected prefix/regex and the actionId string, performs the match, and returns the same shape ({ repo, number } or null) on mismatch; update parseMergeActionId and parseMergeTestToMainActionId to call this utility (preserve their public names and return types) and remove the inline regex/match logic from both functions to avoid duplication.lib/coding-agent/parseMergeTestToMainActionId.ts (1)
4-5: Consider adding a description to the@paramtag.The JSDoc
@paramannotation is present but lacks a description. While TypeScript provides type information, adding a semantic description helps documentation consumers understand the parameter's purpose and expected format.📝 Suggested enhancement
* -* `@param` actionId +* `@param` actionId - The action ID string to parse (format: "merge_test_to_main:owner/repo") */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/coding-agent/parseMergeTestToMainActionId.ts` around lines 4 - 5, The JSDoc for the function in parseMergeTestToMainActionId.ts is missing a description for the `@param` actionId; update the JSDoc block for the function (the symbol handling actionId in parseMergeTestToMainActionId) to include a short semantic description of what actionId represents and its expected format (e.g., "actionId: the workflow run/action identifier string used to map a merge-from-test action to the main action, expected in the form 'owner/repo#runId' or similar"). Ensure the `@param` line describes purpose and any format or validation assumptions.lib/spotify/getSpotifyFollowers.ts (1)
62-65: Consider letting the caller handle error logging.The
console.erroron line 63 logs before re-throwing the error. In library functions, it's often better to let the caller decide how to handle logging, as they may have their own error handling or logging infrastructure. This also avoids duplicate logs if the caller logs the error as well.♻️ Suggested refactor to remove console logging
} catch (error) { - console.error(`Error fetching Spotify followers for "${artistName}":`, error); throw error; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/spotify/getSpotifyFollowers.ts` around lines 62 - 65, The catch block inside getSpotifyFollowers currently calls console.error before re-throwing the error, which forces logging and can cause duplicate logs; remove the console.error(...) call in the catch of getSpotifyFollowers and simply re-throw the error so callers can handle or log it according to their own logging/monitoring strategy.lib/content/contentTemplates.ts (1)
28-31: Complete the JSDoc documentation.The JSDoc comment is essentially a stub with no function description, no parameter description, and no return value documentation. If we're adding documentation, it should provide meaningful information about the function's purpose, parameters, and return value.
📝 Suggested complete JSDoc
/** - * - * `@param` template + * Checks whether the given template name is supported. + * `@param` template - The content template name to validate + * `@returns` True if the template exists in CONTENT_TEMPLATES, false otherwise */ export function isSupportedContentTemplate(template: string): boolean {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/content/contentTemplates.ts` around lines 28 - 31, Replace the stub JSDoc above the function in lib/content/contentTemplates.ts with a full description: add a one-line summary of what the function does, document the parameter "template" with its expected type and shape (e.g., string | TemplateObject) and purpose, and add an `@returns` tag describing the return type and what is returned (e.g., formatted template string or TemplateResult). Also include any thrown errors or side effects if applicable and a short example or note about accepted template formats to aid callers.lib/trigger/triggerCreateContent.ts (1)
19-20: Complete the JSDoc parameter description.The
@paramtag should include a description explaining what the payload contains. Consider adding a brief description that helps developers understand the parameter's purpose.📝 Proposed enhancement to JSDoc
/** * Triggers the create-content task in Trigger.dev. * - * `@param` payload + * `@param` payload - The content creation configuration including account, artist, template, and rendering options */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/trigger/triggerCreateContent.ts` around lines 19 - 20, Update the JSDoc for the function in triggerCreateContent.ts by completing the `@param` tag for the payload parameter: describe what properties the payload contains (e.g., content data, metadata, authorId, or any expected fields), the expected types/shape (briefly), and its purpose (what the function does with the payload) so future developers can understand how to call triggerCreateContent and what to pass in.lib/slack/getBotChannels.ts (1)
12-13: Consider adding parameter descriptions to the JSDoc.The
@param tokenannotation lacks a description of what the token represents.📝 Suggested improvement
/** * Returns all channels the bot is a member of, paginating through all results. * - * `@param` token + * `@param` token - The Slack bot token for authentication */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/slack/getBotChannels.ts` around lines 12 - 13, Update the JSDoc for getBotChannels to document the token parameter: describe that `token` is the Slack Bot OAuth access token (a string used to authenticate API requests) and note any expected format or scope requirements; update the `@param token` line in the comment above the getBotChannels function to include this description and keep style consistent with other JSDoc entries in the file.lib/slack/getBotUserId.ts (1)
11-12: Consider adding parameter descriptions to the JSDoc.The
@param tokenannotation was added but lacks a description. Complete JSDoc documentation improves developer experience by explaining what kind of token is expected.📝 Suggested improvement
/** * Returns the authenticated bot's Slack user ID via auth.test. * - * `@param` token + * `@param` token - The Slack bot token for authentication */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/slack/getBotUserId.ts` around lines 11 - 12, Update the JSDoc for the getBotUserId function to include a clear description for the `@param` token tag (e.g., that it expects a Slack Bot/User OAuth access token or similar), and if missing add descriptions for other tags like `@returns` to clarify what the function returns; locate the JSDoc immediately above the getBotUserId function in lib/slack/getBotUserId.ts and replace the bare "@param token" with a short explanatory sentence describing the expected token format and purpose.lib/slack/getSlackUserInfo.ts (1)
19-21: Consider adding parameter descriptions to the JSDoc.Both
@paramannotations were added without descriptions. Adding descriptions helps developers understand what values to provide.📝 Suggested improvement
/** * Fetches a Slack account's display name and avatar by their Slack ID. * - * `@param` token - * `@param` userId + * `@param` token - The Slack bot token for authentication + * `@param` userId - The Slack user ID to fetch information for */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/slack/getSlackUserInfo.ts` around lines 19 - 21, Add clear descriptions for the JSDoc `@param` annotations in getSlackUserInfo (token and userId) so callers know expected values; update the JSDoc above the getSlackUserInfo function to describe that token is the Slack OAuth/Bot token used for API authentication and userId is the Slack user ID (e.g., "U123...") whose profile is being fetched, and optionally note expected formats or examples and whether either parameter is required.app/api/coding-agent/[platform]/route.ts (2)
13-14: Confusing JSDoc parameter notation.The
@param params.paramstag appears before@param paramsin the documentation, which is confusing and doesn't follow JSDoc best practices. Additionally, the nested property reference lacks a description.Consider either:
- Removing the redundant
params.paramsline sinceparamsalready describes the route parameters- If documenting the nested structure, provide descriptions and maintain proper ordering (parent before children)
📝 Suggested JSDoc improvement
/** * GET /api/coding-agent/[platform] * * Handles webhook verification handshakes (e.g. WhatsApp hub.challenge). * * `@param` request - The incoming verification request - * `@param` params.params * `@param` params - Route params containing the platform name + * `@param` params.params - Awaitable promise resolving to the platform identifier */Or more simply:
/** * GET /api/coding-agent/[platform] * * Handles webhook verification handshakes (e.g. WhatsApp hub.challenge). * * `@param` request - The incoming verification request - * `@param` params.params - * `@param` params - Route params containing the platform name + * `@param` params - Route params promise containing the platform identifier */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/api/coding-agent/`[platform]/route.ts around lines 13 - 14, The JSDoc for the route handler has a redundant/confusing tag: remove the incorrect "@param params.params" line or replace it by documenting the nested property properly; update the block that documents the route parameter `params` (the route handler param named params) so the parent `@param params` appears before any child properties and, if you keep a nested tag, use a property-style tag (e.g., "@param params.platform - description") with a short description for the nested field to clarify the structure.
7-61: JSDoc parameter tags across this PR lack descriptions.Throughout this file and the entire PR,
@paramtags have been added without descriptions. JSDoc documentation should provide meaningful context beyond what the TypeScript signature already conveys. Empty@paramtags offer no value to developers and can actually clutter the documentation.Best practices for JSDoc:
- Include concise descriptions that explain the parameter's purpose or constraints
- If the parameter is self-evident, a brief phrase still helps (e.g.,
@param catalogId - The unique catalog identifier)- Omit
@paramtags entirely if you can't provide useful descriptions—TypeScript types already document the shapeThis applies to all files in this PR:
getContentValidateHandler.ts,getAccountArtistIds.ts,validateGetContentValidateQuery.ts,getCatalogSongs.ts,getCutoffMs.ts,getArtistContentReadiness.ts, andgetArtistFileTree.ts.📚 Examples of meaningful JSDoc
Before (current):
/** * `@param` catalogId * `@param` pageSize * `@param` page */ export async function getCatalogSongs( catalogId: string, pageSize: number = 100, page: number = 1, ): Promise<CatalogSongsResponse>After (improved):
/** * Fetches a paginated list of songs from a catalog. * * `@param` catalogId - The unique identifier of the catalog * `@param` pageSize - Number of songs per page (default: 100) * `@param` page - Page number for pagination (default: 1) * `@param` artistName - Optional filter to show only songs by a specific artist */ export async function getCatalogSongs( catalogId: string, pageSize: number = 100, page: number = 1, artistName?: string, ): Promise<CatalogSongsResponse>🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/api/coding-agent/`[platform]/route.ts around lines 7 - 61, The JSDoc `@param` tags in this file (e.g., GET, POST handlers) and across the listed files (getContentValidateHandler.ts, getAccountArtistIds.ts, validateGetContentValidateQuery.ts, getCatalogSongs.ts, getCutoffMs.ts, getArtistContentReadiness.ts, getArtistFileTree.ts) are empty—either add concise descriptions for each parameter (e.g., "request - incoming NextRequest", "params - route params containing the platform name", or "catalogId - the unique catalog identifier", "pageSize - number of items per page (default: 100)") or remove the `@param` entries entirely when the TypeScript signature is self-explanatory; update the JSDoc blocks for functions like GET, POST and getCatalogSongs to include these short descriptions so docs are meaningful and not cluttered.lib/emails/processAndSendEmail.ts (1)
37-39: Complete the JSDoc parameter description.The
@param inputtag was added but lacks a description, which reduces its documentation value. Consider adding a meaningful description or documenting the nested properties.📝 Suggested enhancement
* -* `@param` input +* `@param` input - Email configuration including recipients, subject, content, and optional room contextOr for more detailed documentation:
* -* `@param` input +* `@param` input - Email configuration object +* `@param` input.to - Recipient email addresses +* `@param` input.subject - Email subject line +* `@param` input.text - Plain text content (converted to HTML via markdown) +* `@param` input.html - Pre-formatted HTML content +* `@param` input.room_id - Optional room ID for footer personalization🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/emails/processAndSendEmail.ts` around lines 37 - 39, Update the JSDoc for the processAndSendEmail function by replacing the empty "@param input" tag with a concise description of the input parameter and its expected shape; either list the key properties the email input object must contain (for example recipient, subject, body, cc/bcc, attachments, metadata) or reference the TypeScript interface/type used for validation (if one exists) so consumers know what to pass into processAndSendEmail.lib/credits/getCreditUsage.ts (1)
11-46: Consider refactoring for Single Responsibility Principle.The function currently handles three distinct concerns: model retrieval, token extraction, and cost calculation. Consider splitting this into focused utilities:
extractTokenCounts(usage: LanguageModelUsage)- handles SDK version compatibilitycalculateCost(inputTokens: number, outputTokens: number, pricing: ModelPricing)- pure calculationgetCreditUsage- orchestrates the aboveThis would improve testability, reusability, and maintainability. Additionally, the current approach of returning
0on all error paths silently masks failures—callers can't distinguish between "no cost" and "calculation failed." Consider returning{ success: boolean, cost: number, error?: string }or throwing errors for truly exceptional cases.As per coding guidelines: "Apply Single Responsibility Principle (SRP): one exported function per file; each file should do one thing well" and "For domain functions, ensure: Single responsibility per function."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/credits/getCreditUsage.ts` around lines 11 - 46, Split getCreditUsage into three responsibilities: add extractTokenCounts(usage: LanguageModelUsage) to normalize inputTokens/outputTokens from SDK v2/v3, add calculateCost(inputTokens: number, outputTokens: number, pricing: ModelPricing) as a pure function that returns the numeric cost, and refactor getCreditUsage to orchestrate: call getModel(modelId), call extractTokenCounts, validate model.pricing, call calculateCost and return a structured result (e.g., { success: boolean, cost: number, error?: string }) instead of always returning 0 on errors; update error paths to populate the error field (or throw for truly exceptional cases) and keep exported functions single-responsibility.lib/launch/validateLaunchBody.ts (1)
25-44: Clean validation function, minor naming consideration.The validation function follows the established pattern well:
safeParse, early return on error withNextResponse, and return validated data on success.One small consideration:
missing_fields(Line 33) receivesfirstError.path, but Zod errors aren't exclusively about missing fields — they could be type mismatches or constraint violations likemin(1). A name likeerror_pathorfield_pathwould be more accurate, though this is a minor nitpick.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/launch/validateLaunchBody.ts` around lines 25 - 44, The response object in validateLaunchBody returns a property named missing_fields but Zod issues.path can represent type/constraint errors too; rename the property to a more accurate name like error_path (or field_path) and update the returned JSON key (and any consumers) accordingly in validateLaunchBody so it reflects the generic error path rather than implying only missing fields.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@app/api/accounts/`[id]/route.ts:
- Around line 26-27: Remove the redundant/ambiguous JSDoc line `@param
params.params` and keep a single clear `@param params` entry that documents the
destructured route params object for the route handler (e.g., explain it
contains the account ID as params.id); update the JSDoc for the route handler
(the function that receives params) so it only has one `@param params`
description and, if helpful, a short `@property` or parenthetical note for `id`
to avoid ambiguity.
In `@app/api/admins/privy/route.ts`:
- Around line 18-20: The empty JSDoc above the OPTIONS handler should be
replaced with a short meaningful description explaining the purpose of the
OPTIONS endpoint and what response/headers it returns; update the comment above
the OPTIONS function (the handler in route.ts) to state that it handles
CORS/preflight requests and lists allowed methods/headers or points to the
response shape so future readers know why it exists.
In `@app/api/launch/route.ts`:
- Around line 45-47: Add an integration test file for the /api/launch route
(e.g., app/api/launch/__tests__/route.test.ts) that exercises the route handler
POST by invoking the exported POST function and the underlying
generateCampaignHandler through realistic NextRequest objects: include tests for
auth failure (mock auth middleware or missing credentials and assert 401),
validation failure (send bodies that fail the launch schema and assert 400 with
validation message), and a successful streaming path (mock dependencies used by
generateCampaignHandler to return a streaming Response and assert stream
contents and status 200). Ensure tests reuse the existing schema
validator/fixtures (validateLaunchBody) and mock any external services or
environment used by generateCampaignHandler so tests are deterministic.
In `@lib/credits/handleChatCredits.ts`:
- Around line 15-20: In the JSDoc for handleChatCredits (in
lib/credits/handleChatCredits.ts) remove the malformed param tags `@param`
usage.usage, `@param` usage.model, and `@param` usage.accountId so only the correct
`@param` entries remain (`@param` usage, `@param` model, `@param` accountId); also
update the description text that currently reads "user's account" to simply
"account" to follow account terminology guidelines. Ensure the cleaned JSDoc
still documents the same parameters (usage, model, accountId) and their
types/descriptions consistently.
In `@lib/github/expandSubmoduleEntries.ts`:
- Around line 14-22: The JSDoc for expandSubmoduleEntries is using malformed
nested `@param` paths (like regularEntries.submoduleEntries and
regularEntries.repo.owner) that don't match the function signature; update the
JSDoc to only declare the top-level parameters regularEntries, submoduleEntries,
and repo, and for repo declare nested fields using repo.owner, repo.repo,
repo.branch (remove any nested paths under regularEntries and submoduleEntries),
ensuring the tags match the destructured parameters used by
expandSubmoduleEntries.
In `@lib/github/resolveSubmodulePath.ts`:
- Around line 9-12: The JSDoc params for resolveSubmodulePath use invalid nested
names like `githubRepo.githubRepo` and `githubRepo.path`; update the comment to
reflect the destructured parameters used by the function (e.g., document `@param
githubRepo` and `@param path` with their types and descriptions) so IDEs and
generated docs show the correct param names for the resolveSubmodulePath
function.
In `@lib/launch/generateCampaignHandler.ts`:
- Around line 22-26: The call to request.json() in generateCampaignHandler can
throw on malformed JSON, so wrap the await request.json() in a try-catch; on
SyntaxError (or any parse error) return a 400 NextResponse with a clear
validation message instead of letting the exception bubble up, then proceed to
call validateLaunchBody(json) and the existing NextResponse handling as before;
reference the request.json() invocation and validateLaunchBody/NextResponse
checks when making this change.
- Around line 28-34: Wrap the request processing and streaming logic in a
try-catch so failures from request.json(), buildCampaignSystemPrompt(),
buildCampaignUserPrompt(), streamText(), or getCorsHeaders() are handled and do
not cause unhandled rejections; specifically, call await request.json() inside
the try, call buildCampaignSystemPrompt() and buildCampaignUserPrompt(validated)
and then streamText(...) there, and use result.toTextStreamResponse(...) on
success, while in the catch return an HTTP 500 (or appropriate) Response with
getCorsHeaders() and an error message (and log the error) so all exceptional
paths are caught and a proper response is returned.
In `@lib/prompts/getSystemPrompt.ts`:
- Line 16: Update the JSDoc for the getSystemPrompt function to add a
description for the params.orgId parameter; locate the JSDoc block above the
getSystemPrompt function and add a one-line description following the same style
as the other params (e.g., "@param params.orgId - the organization identifier
used to customize the system prompt or lookup org-specific settings") so the
documentation is consistent and descriptive.
---
Outside diff comments:
In `@app/api/transcribe/route.ts`:
- Around line 11-33: Replace trusting account_id from the request body with
enforced authentication: call validateAuthContext() at the start of the handler,
drop using body.account_id and instead pass authContext.accountId (or
equivalent) into processAudioTranscription as ownerAccountId; additionally add
input validation using a Zod schema (validate function) to parse/validate
audio_url, title, include_timestamps and artist_account_id (or resolve
artistAccountId from auth if required) before calling processAudioTranscription;
ensure all early returns use NextResponse.json with 400 on schema validation
failures and do not accept account_id from the client.
In `@lib/credits/getCreditUsage.ts`:
- Around line 24-25: Replace the type-unsafe casts and legacy property checks in
getCreditUsage (the inputTokens/outputTokens assignment) by reading the
canonical v6 properties directly: use usage.promptTokens and
usage.completionTokens with a numeric fallback (e.g., ?? 0) instead of casting
to any or checking inputTokens/outputTokens; also update the nearby comment to
state that AI SDK v6 uses promptTokens/completionTokens (not v2/v3 naming) so
future readers know the correct property names.
In `@lib/mcp/tools/transcribe/registerTranscribeAudioTool.ts`:
- Around line 8-13: Remove the caller-supplied account_id from the transcribe
tool input schema and any use in the handler: delete the account_id field from
transcribeAudioSchema and from any request-body parsing, and instead call
resolveAccountId(authContext) inside the registerTranscribeAudioTool handler (or
the function that processes the tool input) to derive and validate the account
ID; ensure any downstream calls that previously used the client-provided
account_id (e.g., storage or DB writes) now receive the resolved value, and
remove/ignore any code paths that accept an explicit artist_account_id override
unless you also validate it against the resolved account via the existing
access-control checks.
In `@lib/transcribe/processAudioTranscription.ts`:
- Around line 18-21: Validate and guard the fetch of caller-controlled audioUrl
in processAudioTranscription: first parse and allowlist the URL scheme/hostname
(reject non-http(s) and hostnames that resolve to private/reserved IPs or
loopback addresses), then perform the fetch with an AbortController-based
timeout (pass signal to fetch) and sensible options (GET, limited redirects) so
slow/unresponsive upstreams are bounded; ensure you handle abort errors and
surface a clear error if validation or the timed fetch fails rather than
directly calling fetch(audioUrl) unguarded.
---
Nitpick comments:
In `@app/api/coding-agent/`[platform]/route.ts:
- Around line 13-14: The JSDoc for the route handler has a redundant/confusing
tag: remove the incorrect "@param params.params" line or replace it by
documenting the nested property properly; update the block that documents the
route parameter `params` (the route handler param named params) so the parent
`@param params` appears before any child properties and, if you keep a nested
tag, use a property-style tag (e.g., "@param params.platform - description")
with a short description for the nested field to clarify the structure.
- Around line 7-61: The JSDoc `@param` tags in this file (e.g., GET, POST
handlers) and across the listed files (getContentValidateHandler.ts,
getAccountArtistIds.ts, validateGetContentValidateQuery.ts, getCatalogSongs.ts,
getCutoffMs.ts, getArtistContentReadiness.ts, getArtistFileTree.ts) are
empty—either add concise descriptions for each parameter (e.g., "request -
incoming NextRequest", "params - route params containing the platform name", or
"catalogId - the unique catalog identifier", "pageSize - number of items per
page (default: 100)") or remove the `@param` entries entirely when the TypeScript
signature is self-explanatory; update the JSDoc blocks for functions like GET,
POST and getCatalogSongs to include these short descriptions so docs are
meaningful and not cluttered.
In `@lib/admins/privy/getLatestVerifiedAt.ts`:
- Line 8: Update the JSDoc for getLatestVerifiedAt to use the
repository-approved terminology by renaming the param from "user" to "account"
and add a short description; specifically, change the `@param` tag to "@param
account" and include one-line text describing that account is the Account object
or identifier passed into getLatestVerifiedAt so the doc follows the project's
"account" terminology and clarifies the parameter purpose.
In `@lib/catalog/getCatalogs.ts`:
- Around line 11-14: Add complete JSDoc for the getCatalogs function: write a
one-line description of what getCatalogs does, add `@param` accountId with its
type and description, document the return value (e.g., Promise of the catalog
array or specific Catalog type) with `@returns` and describe possible thrown
errors or null cases, and include any side effects; place this above the
getCatalogs function declaration in lib/catalog/getCatalogs.ts so the function
signature and return type (getCatalogs) are clearly described for callers and
maintainers.
In `@lib/coding-agent/handleMergeSuccess.ts`:
- Around line 10-11: The JSDoc for the handleMergeSuccess function has an
incomplete `@param` tag for "state"; update the comment above handleMergeSuccess
in lib/coding-agent/handleMergeSuccess.ts to add a concise description of what
the "state" parameter represents (e.g., current merge operation context,
contains branch names, commit metadata, and status flags) so readers can
understand its purpose without opening the type definition.
In `@lib/coding-agent/parseMergeActionId.ts`:
- Around line 4-5: The JSDoc for parseMergeActionId is missing a description for
the `@param` actionId; update the function's JSDoc block (the one above
parseMergeActionId) to describe what actionId should contain (e.g., expected
type, format, and any accepted patterns such as "merge:<repo>:<prId>" or a UUID)
so callers know the input shape and constraints.
- Around line 7-11: parseMergeActionId duplicates parsing logic used by
parseMergeTestToMainActionId; create a shared utility (e.g.,
parsePrefixedActionId or parseActionIdWithRegex) that accepts the expected
prefix/regex and the actionId string, performs the match, and returns the same
shape ({ repo, number } or null) on mismatch; update parseMergeActionId and
parseMergeTestToMainActionId to call this utility (preserve their public names
and return types) and remove the inline regex/match logic from both functions to
avoid duplication.
In `@lib/coding-agent/parseMergeTestToMainActionId.ts`:
- Around line 4-5: The JSDoc for the function in parseMergeTestToMainActionId.ts
is missing a description for the `@param` actionId; update the JSDoc block for the
function (the symbol handling actionId in parseMergeTestToMainActionId) to
include a short semantic description of what actionId represents and its
expected format (e.g., "actionId: the workflow run/action identifier string used
to map a merge-from-test action to the main action, expected in the form
'owner/repo#runId' or similar"). Ensure the `@param` line describes purpose and
any format or validation assumptions.
In `@lib/composio/getCallbackUrl.ts`:
- Line 22: Move the JSDoc `@param` for the parent "options" above the child params
(options.destination and options.roomId) and add a short description; update the
JSDoc block for the getCallbackUrl (or the exported function in
getCallbackUrl.ts) so it lists "@param options - an object containing callback
configuration" (or similar concise text) before "@param options.destination" and
"@param options.roomId" to keep param order logical and improve generated docs.
In `@lib/content/contentTemplates.ts`:
- Around line 28-31: Replace the stub JSDoc above the function in
lib/content/contentTemplates.ts with a full description: add a one-line summary
of what the function does, document the parameter "template" with its expected
type and shape (e.g., string | TemplateObject) and purpose, and add an `@returns`
tag describing the return type and what is returned (e.g., formatted template
string or TemplateResult). Also include any thrown errors or side effects if
applicable and a short example or note about accepted template formats to aid
callers.
In `@lib/content/isCompletedRun.ts`:
- Around line 8-11: Update the empty JSDoc block above the isCompletedRun
function to include a short summary sentence describing what the function does
(e.g., checks whether a run is finished), a concrete `@param` entry for the run
parameter explaining expected shape or properties used (e.g., status field or
timestamps) and how it is interpreted, and an `@returns` description specifying
the boolean result and what true/false mean; reference the isCompletedRun
identifier so the doc directly documents that function's behavior.
In `@lib/credits/getCreditUsage.ts`:
- Around line 11-46: Split getCreditUsage into three responsibilities: add
extractTokenCounts(usage: LanguageModelUsage) to normalize
inputTokens/outputTokens from SDK v2/v3, add calculateCost(inputTokens: number,
outputTokens: number, pricing: ModelPricing) as a pure function that returns the
numeric cost, and refactor getCreditUsage to orchestrate: call
getModel(modelId), call extractTokenCounts, validate model.pricing, call
calculateCost and return a structured result (e.g., { success: boolean, cost:
number, error?: string }) instead of always returning 0 on errors; update error
paths to populate the error field (or throw for truly exceptional cases) and
keep exported functions single-responsibility.
In `@lib/emails/processAndSendEmail.ts`:
- Around line 37-39: Update the JSDoc for the processAndSendEmail function by
replacing the empty "@param input" tag with a concise description of the input
parameter and its expected shape; either list the key properties the email input
object must contain (for example recipient, subject, body, cc/bcc, attachments,
metadata) or reference the TypeScript interface/type used for validation (if one
exists) so consumers know what to pass into processAndSendEmail.
In `@lib/flamingo/getFlamingoPresetsHandler.ts`:
- Line 13: Add a concise description to the JSDoc `@param` for the request
parameter in getFlamingoPresetsHandler: state what the request represents (e.g.,
incoming Express/HTTP request or handler input), what properties are
expected/used (if any), and its role in the function; update the JSDoc `@param`
line to read something like "@param request - the incoming request object
containing [brief properties or purpose]" so it matches the existing `@returns`
documentation and clarifies the parameter's purpose.
In `@lib/github/getRepoGitModules.ts`:
- Around line 7-12: The JSDoc for getRepoGitModules.ts uses inconsistent param
names (both flat tags like `@param` owner/@param repo/@param branch and erroneous
nested tags like `@param` owner.owner/@param owner.repo/@param owner.branch);
remove the nested/duplicate tags and ensure the JSDoc matches the function
signature (document the destructured param either as a single object with a type
description or keep separate `@param` entries for owner, repo, branch) so that
only the correct identifiers used in the function (owner, repo, branch) are
documented.
In `@lib/launch/validateLaunchBody.ts`:
- Around line 25-44: The response object in validateLaunchBody returns a
property named missing_fields but Zod issues.path can represent type/constraint
errors too; rename the property to a more accurate name like error_path (or
field_path) and update the returned JSON key (and any consumers) accordingly in
validateLaunchBody so it reflects the generic error path rather than implying
only missing fields.
In `@lib/slack/getBotChannels.ts`:
- Around line 12-13: Update the JSDoc for getBotChannels to document the token
parameter: describe that `token` is the Slack Bot OAuth access token (a string
used to authenticate API requests) and note any expected format or scope
requirements; update the `@param token` line in the comment above the
getBotChannels function to include this description and keep style consistent
with other JSDoc entries in the file.
In `@lib/slack/getBotUserId.ts`:
- Around line 11-12: Update the JSDoc for the getBotUserId function to include a
clear description for the `@param` token tag (e.g., that it expects a Slack
Bot/User OAuth access token or similar), and if missing add descriptions for
other tags like `@returns` to clarify what the function returns; locate the JSDoc
immediately above the getBotUserId function in lib/slack/getBotUserId.ts and
replace the bare "@param token" with a short explanatory sentence describing the
expected token format and purpose.
In `@lib/slack/getSlackUserInfo.ts`:
- Around line 19-21: Add clear descriptions for the JSDoc `@param` annotations in
getSlackUserInfo (token and userId) so callers know expected values; update the
JSDoc above the getSlackUserInfo function to describe that token is the Slack
OAuth/Bot token used for API authentication and userId is the Slack user ID
(e.g., "U123...") whose profile is being fetched, and optionally note expected
formats or examples and whether either parameter is required.
In `@lib/spotify/getSpotifyFollowers.ts`:
- Around line 62-65: The catch block inside getSpotifyFollowers currently calls
console.error before re-throwing the error, which forces logging and can cause
duplicate logs; remove the console.error(...) call in the catch of
getSpotifyFollowers and simply re-throw the error so callers can handle or log
it according to their own logging/monitoring strategy.
In `@lib/supabase/files/createFileRecord.ts`:
- Around line 28-30: The JSDoc for the exported Supabase function
createFileRecord is too terse—replace the generic "@param params" with an
object-level description and explicit key descriptions (e.g., params.bucket,
params.key or path, params.size, params.mimeType/contentType,
params.userId/uploaderId, params.metadata/extra) so callers know the contract;
update the comment block above createFileRecord to list each field, types and
short intent (required/optional) and ensure it follows the project pattern for
Supabase domain functions importing from "@/lib/supabase/serverClient".
In `@lib/supabase/storage/uploadFileByKey.ts`:
- Around line 7-11: Update the JSDoc for the upload function (e.g.,
uploadFileByKey) to include meaningful descriptions for each param: describe key
as the storage path/OCI-style path or bucket-relative path semantics (e.g.,
"bucket/path/to/file.ext"), file as the File/Blob or Buffer to be uploaded,
options as an optional object controlling upload behavior, options.contentType
with its default (e.g., "application/octet-stream" or infer from filename) and
expected MIME string format, and options.upsert with default false and that it
controls overwrite behavior; also ensure the function follows the Supabase
pattern by importing the server client from "@/lib/supabase/serverClient" and
that the JSDoc mentions thrown errors/return type consistent with other Supabase
helpers (e.g., upload result or error).
In `@lib/trigger/triggerCreateContent.ts`:
- Around line 19-20: Update the JSDoc for the function in
triggerCreateContent.ts by completing the `@param` tag for the payload parameter:
describe what properties the payload contains (e.g., content data, metadata,
authorId, or any expected fields), the expected types/shape (briefly), and its
purpose (what the function does with the payload) so future developers can
understand how to call triggerCreateContent and what to pass in.
| * @param params.params | ||
| * @param params - Route params containing the account ID |
There was a problem hiding this comment.
Fix redundant/ambiguous JSDoc param annotation.
@param params.params is unclear and overlaps with @param params. Keep one clear param entry for the destructured route params object.
Suggested JSDoc cleanup
- * `@param` params.params
- * `@param` params - Route params containing the account ID
+ * `@param` params - Route params promise containing the account ID📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| * @param params.params | |
| * @param params - Route params containing the account ID | |
| * `@param` params - Route params containing the account ID |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@app/api/accounts/`[id]/route.ts around lines 26 - 27, Remove the
redundant/ambiguous JSDoc line `@param params.params` and keep a single clear
`@param params` entry that documents the destructured route params object for
the route handler (e.g., explain it contains the account ID as params.id);
update the JSDoc for the route handler (the function that receives params) so it
only has one `@param params` description and, if helpful, a short `@property` or
parenthetical note for `id` to avoid ambiguity.
| /** | ||
| * | ||
| */ |
There was a problem hiding this comment.
Replace empty JSDoc block with a meaningful description.
The empty comment block on OPTIONS adds noise without context; please document purpose/response briefly.
Suggested doc improvement
-/**
- *
- */
+/**
+ * CORS preflight handler for /api/admins/privy.
+ *
+ * `@returns` 204 response with CORS headers.
+ */📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** | |
| * | |
| */ | |
| /** | |
| * CORS preflight handler for /api/admins/privy. | |
| * | |
| * `@returns` 204 response with CORS headers. | |
| */ |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@app/api/admins/privy/route.ts` around lines 18 - 20, The empty JSDoc above
the OPTIONS handler should be replaced with a short meaningful description
explaining the purpose of the OPTIONS endpoint and what response/headers it
returns; update the comment above the OPTIONS function (the handler in route.ts)
to state that it handles CORS/preflight requests and lists allowed
methods/headers or points to the response shape so future readers know why it
exists.
| export async function POST(request: NextRequest): Promise<Response> { | ||
| return generateCampaignHandler(request); | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for test files covering the launch endpoint
echo "=== Looking for launch-related test files ==="
fd -e test.ts -e spec.ts launch
echo ""
echo "=== Searching for tests referencing /api/launch ==="
rg -l "api/launch" --glob "*test*" --glob "*spec*"
echo ""
echo "=== Searching for generateCampaignHandler tests ==="
rg -l "generateCampaignHandler" --glob "*test*" --glob "*spec*"Repository: recoupable/api
Length of output: 257
🏁 Script executed:
# Search for all test files in the repository
find . -type f \( -name "*.test.ts" -o -name "*.spec.ts" -o -name "*.integration.ts" -o -name "*.e2e.ts" \) | head -30Repository: recoupable/api
Length of output: 1735
🏁 Script executed:
# Check the structure of app/api directory and look for test patterns
fd -t f -e ts -e tsx "app/api" | grep -i testRepository: recoupable/api
Length of output: 391
🏁 Script executed:
# Search for where generateCampaignHandler is defined and if it has any tests
rg "generateCampaignHandler" -A 5 -B 2 | head -50Repository: recoupable/api
Length of output: 1573
🏁 Script executed:
# Check if launch route test file exists
ls -la app/api/launch/__tests__/ 2>/dev/null || echo "Directory does not exist"
# Search for any test files in launch directory
find app/api/launch -name "*.test.ts" -o -name "*.spec.ts" 2>/dev/null || echo "No test files found"
# Confirm the pattern - check if other api endpoints have __tests__ directories with route.test.ts
ls -1 app/api/*/__tests__/route.test.ts 2>/dev/null | head -5Repository: recoupable/api
Length of output: 127
🏁 Script executed:
# Get more details on the generateCampaignHandler implementation to understand what needs testing
cat -n lib/launch/generateCampaignHandler.ts | head -60Repository: recoupable/api
Length of output: 1549
Add integration tests for the /api/launch endpoint covering all success and error paths.
Integration tests are missing for this route handler. The codebase has validateLaunchBody.test.ts for schema validation, but lacks tests for the route handler itself (auth failures, validation failures, successful streaming). Other API endpoints in the codebase follow the established pattern with app/api/**/__tests__/route.test.ts files.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@app/api/launch/route.ts` around lines 45 - 47, Add an integration test file
for the /api/launch route (e.g., app/api/launch/__tests__/route.test.ts) that
exercises the route handler POST by invoking the exported POST function and the
underlying generateCampaignHandler through realistic NextRequest objects:
include tests for auth failure (mock auth middleware or missing credentials and
assert 401), validation failure (send bodies that fail the launch schema and
assert 400 with validation message), and a successful streaming path (mock
dependencies used by generateCampaignHandler to return a streaming Response and
assert stream contents and status 200). Ensure tests reuse the existing schema
validator/fixtures (validateLaunchBody) and mock any external services or
environment used by generateCampaignHandler so tests are deterministic.
| * @param usage.usage | ||
| * @param usage - The language model usage data | ||
| * @param model - The model ID used for the chat | ||
| * @param accountId - The account ID to deduct credits from (optional) | ||
| * @param usage.model | ||
| * @param usage.accountId |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify malformed JSDoc param paths and forbidden terminology in TS files.
rg -n --type=ts '@param\s+usage\.'
rg -n --type=ts "user's account| user " lib/credits/handleChatCredits.tsRepository: recoupable/api
Length of output: 320
🏁 Script executed:
cat -n lib/credits/handleChatCredits.ts | head -30Repository: recoupable/api
Length of output: 1127
🏁 Script executed:
# Verify if removing malformed JSDoc entries and fixing terminology would resolve the comment
# Check for similar patterns in other files to assess broader impact
rg -n '@param\s+\w+\.\w+' lib/credits/ lib/mcp/tools/ --type=ts -A 2 -B 2Repository: recoupable/api
Length of output: 4417
Remove malformed JSDoc entries and fix account terminology.
Lines 15, 19, and 20 contain malformed @param entries (@param usage.usage, @param usage.model, @param usage.accountId) that conflict with the correct documentation on lines 16-18. These should be removed. Additionally, line 13 violates account terminology guidelines—change "user's account" to "account".
🛠️ Suggested fix
/**
* Handles credit deduction after chat completion.
- * Calculates usage cost and deducts appropriate credits from the user's account.
+ * Calculates usage cost and deducts appropriate credits from the account.
*
- * `@param` usage.usage
* `@param` usage - The language model usage data
* `@param` model - The model ID used for the chat
* `@param` accountId - The account ID to deduct credits from (optional)
- * `@param` usage.model
- * `@param` usage.accountId
*/📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| * @param usage.usage | |
| * @param usage - The language model usage data | |
| * @param model - The model ID used for the chat | |
| * @param accountId - The account ID to deduct credits from (optional) | |
| * @param usage.model | |
| * @param usage.accountId | |
| /** | |
| * Handles credit deduction after chat completion. | |
| * Calculates usage cost and deducts appropriate credits from the account. | |
| * | |
| * `@param` usage - The language model usage data | |
| * `@param` model - The model ID used for the chat | |
| * `@param` accountId - The account ID to deduct credits from (optional) | |
| */ |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/credits/handleChatCredits.ts` around lines 15 - 20, In the JSDoc for
handleChatCredits (in lib/credits/handleChatCredits.ts) remove the malformed
param tags `@param` usage.usage, `@param` usage.model, and `@param` usage.accountId so
only the correct `@param` entries remain (`@param` usage, `@param` model, `@param`
accountId); also update the description text that currently reads "user's
account" to simply "account" to follow account terminology guidelines. Ensure
the cleaned JSDoc still documents the same parameters (usage, model, accountId)
and their types/descriptions consistently.
| * @param regularEntries.regularEntries | ||
| * @param regularEntries - Non-submodule file tree entries | ||
| * @param submoduleEntries - Submodule references (type "commit" from GitHub Trees API) | ||
| * @param repo - Repository context for fetching .gitmodules | ||
| * @param regularEntries.submoduleEntries | ||
| * @param regularEntries.repo | ||
| * @param regularEntries.repo.owner | ||
| * @param regularEntries.repo.repo | ||
| * @param regularEntries.repo.branch |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify this file no longer contains malformed `@param` paths and has expected repo nested docs.
set -euo pipefail
FILE="lib/github/expandSubmoduleEntries.ts"
echo "Checking for malformed JSDoc `@param` paths..."
rg -n '@param\s+regularEntries\.(regularEntries|submoduleEntries|repo(\.|$))' "$FILE" || true
echo "Checking expected nested repo tags..."
rg -n '@param\s+repo\.(owner|repo|branch)\b' "$FILE"Repository: recoupable/api
Length of output: 378
🏁 Script executed:
cat -n lib/github/expandSubmoduleEntries.ts | head -40Repository: recoupable/api
Length of output: 1744
Fix malformed nested JSDoc @param paths.
The new tags don't match the function signature. regularEntries and submoduleEntries are array parameters, so entries like regularEntries.submoduleEntries and regularEntries.repo.owner are invalid. Use only top-level params for the destructured object fields (regularEntries, submoduleEntries, repo) and add nested paths only under repo (e.g., repo.owner, repo.repo, repo.branch).
🛠️ Suggested JSDoc fix
- * `@param` regularEntries.regularEntries
* `@param` regularEntries - Non-submodule file tree entries
* `@param` submoduleEntries - Submodule references (type "commit" from GitHub Trees API)
* `@param` repo - Repository context for fetching .gitmodules
- * `@param` regularEntries.submoduleEntries
- * `@param` regularEntries.repo
- * `@param` regularEntries.repo.owner
- * `@param` regularEntries.repo.repo
- * `@param` regularEntries.repo.branch
+ * `@param` repo.owner - Repository owner
+ * `@param` repo.repo - Repository name
+ * `@param` repo.branch - Repository branch📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| * @param regularEntries.regularEntries | |
| * @param regularEntries - Non-submodule file tree entries | |
| * @param submoduleEntries - Submodule references (type "commit" from GitHub Trees API) | |
| * @param repo - Repository context for fetching .gitmodules | |
| * @param regularEntries.submoduleEntries | |
| * @param regularEntries.repo | |
| * @param regularEntries.repo.owner | |
| * @param regularEntries.repo.repo | |
| * @param regularEntries.repo.branch | |
| * `@param` regularEntries - Non-submodule file tree entries | |
| * `@param` submoduleEntries - Submodule references (type "commit" from GitHub Trees API) | |
| * `@param` repo - Repository context for fetching .gitmodules | |
| * `@param` repo.owner - Repository owner | |
| * `@param` repo.repo - Repository name | |
| * `@param` repo.branch - Repository branch |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/github/expandSubmoduleEntries.ts` around lines 14 - 22, The JSDoc for
expandSubmoduleEntries is using malformed nested `@param` paths (like
regularEntries.submoduleEntries and regularEntries.repo.owner) that don't match
the function signature; update the JSDoc to only declare the top-level
parameters regularEntries, submoduleEntries, and repo, and for repo declare
nested fields using repo.owner, repo.repo, repo.branch (remove any nested paths
under regularEntries and submoduleEntries), ensuring the tags match the
destructured parameters used by expandSubmoduleEntries.
| * @param githubRepo.githubRepo | ||
| * @param githubRepo - The parent GitHub repository URL | ||
| * @param path - The file path to resolve | ||
| * @param githubRepo.path |
There was a problem hiding this comment.
Fix invalid/misleading JSDoc param paths for destructured args.
Line 9 and Line 12 currently document githubRepo.githubRepo / githubRepo.path, but the function takes a destructured object, not a nested githubRepo object parameter. This can confuse IDE docs and generated API docs.
🛠️ Proposed JSDoc fix
/**
* Resolves a file path that may be inside a git submodule.
* If the path falls within a submodule, returns the submodule's repo URL
* and the relative path within it. Otherwise returns the original values.
*
- * `@param` githubRepo.githubRepo
- * `@param` githubRepo - The parent GitHub repository URL
- * `@param` path - The file path to resolve
- * `@param` githubRepo.path
+ * `@param` params - Resolver input
+ * `@param` params.githubRepo - The parent GitHub repository URL
+ * `@param` params.path - The file path to resolve
* `@returns` The resolved repo URL and path
*/🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/github/resolveSubmodulePath.ts` around lines 9 - 12, The JSDoc params for
resolveSubmodulePath use invalid nested names like `githubRepo.githubRepo` and
`githubRepo.path`; update the comment to reflect the destructured parameters
used by the function (e.g., document `@param githubRepo` and `@param path` with
their types and descriptions) so IDEs and generated docs show the correct param
names for the resolveSubmodulePath function.
| const json = await request.json(); | ||
| const validated = validateLaunchBody(json); | ||
| if (validated instanceof NextResponse) { | ||
| return validated; | ||
| } |
There was a problem hiding this comment.
Missing try-catch around request.json() — malformed JSON will cause unhandled 500.
If the client sends invalid JSON (e.g., truncated body, wrong content-type), request.json() throws a SyntaxError. This bubbles up as an unhandled exception resulting in a 500 response rather than a clean 400 error.
🛡️ Proposed fix to handle JSON parse errors
+ let json: unknown;
+ try {
+ json = await request.json();
+ } catch {
+ return NextResponse.json(
+ { status: "error", error: "Invalid JSON body" },
+ { status: 400, headers: getCorsHeaders() },
+ );
+ }
- const json = await request.json();
const validated = validateLaunchBody(json);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const json = await request.json(); | |
| const validated = validateLaunchBody(json); | |
| if (validated instanceof NextResponse) { | |
| return validated; | |
| } | |
| let json: unknown; | |
| try { | |
| json = await request.json(); | |
| } catch { | |
| return NextResponse.json( | |
| { status: "error", error: "Invalid JSON body" }, | |
| { status: 400, headers: getCorsHeaders() }, | |
| ); | |
| } | |
| const validated = validateLaunchBody(json); | |
| if (validated instanceof NextResponse) { | |
| return validated; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/launch/generateCampaignHandler.ts` around lines 22 - 26, The call to
request.json() in generateCampaignHandler can throw on malformed JSON, so wrap
the await request.json() in a try-catch; on SyntaxError (or any parse error)
return a 400 NextResponse with a clear validation message instead of letting the
exception bubble up, then proceed to call validateLaunchBody(json) and the
existing NextResponse handling as before; reference the request.json()
invocation and validateLaunchBody/NextResponse checks when making this change.
| const result = streamText({ | ||
| model: DEFAULT_MODEL, | ||
| system: buildCampaignSystemPrompt(), | ||
| prompt: buildCampaignUserPrompt(validated), | ||
| }); | ||
|
|
||
| return result.toTextStreamResponse({ headers: getCorsHeaders() }); |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Vercel AI SDK streamText toTextStreamResponse v6
💡 Result:
In Vercel AI SDK v6 (released December 2025), streamText from 'ai' generates a streaming text response from an LLM. The result object includes toTextStreamResponse, which creates a simple text stream HTTP response for use in API routes, such as Next.js App Router. Usage example in an API route: import { streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; export async function POST(req: Request) { const { messages } = await req.json; const result = streamText({ model: openai('gpt-4o-mini'), messages, }); return result.toTextStreamResponse; } This streams plain text deltas. For UI message streams (with tool calls), use toUIMessageStreamResponse. On the client, consume with useChat({ streamProtocol: 'text' }). The API remains consistent from prior versions with minimal breaking changes; use npx @ai-sdk/codemod v6 for migration. Official docs: https://v6.ai-sdk.dev/docs/ai-sdk-core/generating-text and https://ai-sdk.dev/docs/ai-sdk-core/generating-text (v6 docs mirror structure).
Citations:
- 1: https://v6.ai-sdk.dev/docs/ai-sdk-core/generating-text
- 2: https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
- 3: https://ai-sdk.dev/docs/ai-sdk-core/generating-text
- 4: https://vercel.com/kb/guide/streaming-from-llm
- 5: streamProtocol: "text", not working with useChat & toTextStreamResponse vercel/ai#2576
- 6: https://vercel.com/blog/ai-sdk-6
🏁 Script executed:
cat -n lib/launch/generateCampaignHandler.tsRepository: recoupable/api
Length of output: 1549
Add error handling for potential failures in streamText() and auxiliary function calls.
The Vercel AI SDK v6 usage is correct—streamText with model, system, and prompt parameters and toTextStreamResponse() follow the proper pattern. However, the function lacks error handling for:
request.json()(line 22)—can throw if body is invalid or missingstreamText()(line 28)buildCampaignSystemPrompt()andbuildCampaignUserPrompt()(lines 30–31)getCorsHeaders()(line 34)
Wrap these calls in try-catch to prevent unhandled rejections from crashing the request.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/launch/generateCampaignHandler.ts` around lines 28 - 34, Wrap the request
processing and streaming logic in a try-catch so failures from request.json(),
buildCampaignSystemPrompt(), buildCampaignUserPrompt(), streamText(), or
getCorsHeaders() are handled and do not cause unhandled rejections;
specifically, call await request.json() inside the try, call
buildCampaignSystemPrompt() and buildCampaignUserPrompt(validated) and then
streamText(...) there, and use result.toTextStreamResponse(...) on success,
while in the catch return an HTTP 500 (or appropriate) Response with
getCorsHeaders() and an error message (and log the error) so all exceptional
paths are caught and a proper response is returned.
| * @param params.artistInstruction - The artist instruction | ||
| * @param params.conversationName - The name of the conversation | ||
| * @param params.accountWithDetails - The account with details | ||
| * @param params.orgId |
There was a problem hiding this comment.
Add description to the JSDoc parameter.
The JSDoc for params.orgId is missing a description, which is inconsistent with all other parameter documentation in this function. Each parameter should have a clear description following the pattern used for other params.
📝 Suggested fix
- * `@param` params.orgId
+ * `@param` params.orgId - The ID of the organization (optional, defaults to personal account)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| * @param params.orgId | |
| * `@param` params.orgId - The ID of the organization (optional, defaults to personal account) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/prompts/getSystemPrompt.ts` at line 16, Update the JSDoc for the
getSystemPrompt function to add a description for the params.orgId parameter;
locate the JSDoc block above the getSystemPrompt function and add a one-line
description following the same style as the other params (e.g., "@param
params.orgId - the organization identifier used to customize the system prompt
or lookup org-specific settings") so the documentation is consistent and
descriptive.
Automated PR from coding agent.
Summary by CodeRabbit
Release Notes
New Features
Documentation